package com.meng.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;


/**
 * Jedis 工具类
 *
 * @author MENG
 * @version 2017/12/5
 * @see
 */
public class JedisUtils
{
    public static void getKeys(Jedis jedis)
    {
        Set<String> set = jedis.keys("*");

        if (set.size() != 0)
        {
            Iterator<String> it = set.iterator();

            while (it.hasNext())
            {
                String key = it.next();

                System.out.println(key);
            }

        }
        else
        {
            System.out.println("数据库暂时没有数据");
        }
    }

    /**
     * 获取redis上所有的key  慎用 数据量大的话会很可怕
     *
     * @param jedisCluster jedisCluster 对象
     * @param pattern
     * @return
     */
    public static TreeSet<String> JedisClusterKeys(JedisCluster jedisCluster, String pattern)
    {

        TreeSet<String> keys = new TreeSet<>();

        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();

        for(String k : clusterNodes.keySet())
        {
            JedisPool jp = clusterNodes.get(k);

            Jedis connection = jp.getResource();

            try
            {
                keys.addAll(connection.keys(pattern));
            }
            catch(Exception e)
            {
                e.printStackTrace();//  logger
            }
            finally
            {
                connection.close();//用完一定要close这个链接！！！
            }
        }
        return keys;
    }



}
